<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\controller\Api;
use app\common\model\Order as OrderModel;
use app\admin\model\Play as PlayModel;
use app\common\model\OrderLog;
use app\api\service\UserService;
use app\common\model\User;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Cront extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 店铺生成前一天的账单
     * @return [type] [description]
     */
    public function createBill()
    {
        /**
         * 所有已完成未支付的订单
         * 近3天所有发布活动的店铺
         * 
         */
        $token = $this->request->param('token');
        if (!$token) exit;
        if (!Db::name('admin')->where('token2',$token)->find()) exit;
        $date = date('Y-m-d');// 今天0点
        $time = strtotime($date);
        $last3time = $time-259200;
        $last3date = date('Y-m-d H:i:s',$last3time);
        $create_dt = date('Y-m-d H:i:s');
        // $shops = Db::name('play')->field('shop_no')->where('create_dt>"'.$last3date.'" and create_dt<="'.date('Y-m-d H:i:s').'"')->group('shop_no')->select();
        $shops = Db::name('play_order')->field('shop_no')->where('order_status in (3,6,-9) and create_dt<"'.$date.'"')->group('shop_no')->select();
        $list = [];
        if ($shops) {
            foreach ($shops as $key => $row) {
                $shop = Db::name('shop')->where('shop_no',$row['shop_no'])->field('shop_name,id,have_uid,salesman_admin_id,shop_area,shop_type,shop_no')->find();
                if (!$shop) continue;
                $list[$key]['shop_id'] = $shop['id'];
                $list[$key]['shop_no'] = $shop['shop_no'];
                $list[$key]['service_admin_id'] = $shop['salesman_admin_id'];
                $list[$key]['service_admin_by'] = Db::name('admin')->where('id',$shop['salesman_admin_id'])->value('nickname');
                if (!$list[$key]['service_admin_by']) {
                    $list[$key]['service_admin_by'] = '';
                }
                $list[$key]['shop_area'] = $shop['shop_area'];
                $list[$key]['user_id'] = $shop['have_uid']+config('virtual_userid');
                $shop_type = config('platform')[$shop['shop_type']];
                $list[$key]['shop_name'] = $shop['shop_name'].'（'.$shop_type.'）';
                $play_status = '正常';
                $num = 0;
                $order = Db::name('play_order')->field('*')->where(['shop_no'=>$row['shop_no']])->where('order_status in (3,6,-9) and create_dt<"'.$date.'"')->order('pay_time DESC')->find();
                $last_pay_time = intval($order['pay_time']);// 到账时间
                // $list[$key]['create_dt'] = $last3date;

                // $order = Db::name('play_order')->field('*')->where(['shop_no'=>$row['shop_no']])->where('order_status=-7')->order('id DESC')->find();
                // if ($order) {
                //     $play_status .= '，异常账单';
                // }
                $order = Db::name('play_order')->field('sum(actual_rebate_amt) as actual_rebate_amt,sum(service_charge_amt) as service_charge_amt,create_dt')->where(['shop_no'=>$row['shop_no']])->where('is_pay=0 and order_status in (3,6,-9) and create_dt<"'.$date.'"')->order('create_dt asc')->find();
                $list[$key]['nopay_dt'] = '1970-01-01 00:00:00';
                if ($order) {
                    $num = $order['actual_rebate_amt']+$order['service_charge_amt'];
                    if ($num>0) {
                        $list[$key]['nopay_dt'] = $order['create_dt'];
                    }
                    $timediff = $time-strtotime($order['create_dt']);
                    if ($timediff>259200) {
                        $play_status = '紧急账单';
                    }
                    if ($timediff>777600) {
                        $play_status = '异常账单';
                    }
                }
                // $play = Db::name('play_order')->where('order_status in (3,-9) and shop_no='.$row['shop_no'].' and is_pay=0')->where('create_dt<"'.date('Y-m-d H:i:s',$time-259200).'"')->count();
                // if ($play) {
                //     $play_status = '紧急账单';
                // }
                // $play = Db::name('play_order')->where('order_status in (3,-9) and shop_no='.$row['shop_no'].' and is_pay=0')->where('create_dt<"'.date('Y-m-d H:i:s',$time-777600).'"')->count();
                // if ($play) {
                //     $play_status = '异常账单';
                // }
                // if ($num>1000) {
                //     $play_status .= '，大额账单';
                // }
                $list[$key]['last_pay_time'] = 0;
                $list[$key]['total_money'] = 0;
                $list[$key]['pay_status'] = '';
                if ($num>0) {
                    $list[$key]['pay_status'] = '待支付';
                    $list[$key]['total_money'] = round($num,2);
                } else {
                    $list[$key]['pay_status'] = '已支付';
                    $list[$key]['last_pay_time'] = $last_pay_time;
                }
                $list[$key]['play_status'] = $play_status;
                $list[$key]['create_dt'] = $create_dt;
                Db::name('bill_list')->insert($list[$key]);
            }
        }
        $this->success('生成账单成功');
    }

    /**
     * 员工业绩
     * @return [type] [description]
     */
    public function employeePerformance()
    {
        $middleman = Db::name('middleman')->field('id,rebate_amt')->select();
        $rebate_amt = [];
        foreach ($middleman as $v) {
            $rebate_amt[$v['id']] = $v['rebate_amt'];
        }
        $admin = Db::name('auth_group_access')->alias('aga')->join('chbc_admin a','aga.uid=a.id')->where(['aga.group_id'=>3])->select();
        $start_date = date('Y-m-01 00:00:00',strtotime('-1 month'));
        $end_date = date("Y-m-d 23:59:59", strtotime(-date('d').'day'));
        $list = [];
        foreach ($admin as $key => $value) {
            $where2 = 'salesman_admin_id='.$value['id'].' and create_dt>="'.$start_date.'" and create_dt<"'.$end_date.'"';
            $where3 = 'p.salesman_admin_id='.$value['id'].' and s.create_dt>="'.$start_date.'" and s.create_dt<"'.$end_date.'"';
            $where4 = 'p.salesman_admin_id='.$value['id'].' and po.create_dt>="'.$start_date.'" and po.create_dt<"'.$end_date.'"';
            // 新增商家
            $xzsj = Db::name('shop')->where(['shop_status'=>1])->where($where2)->count();
            // 优质店铺:满返条件差价小于或等于3的店铺
            $zxyzdp = Db::name('shop')->alias('s')->join('chbc_play p','p.shop_no=s.shop_no')->where('s.shop_status=1 and p.play_status in (1,2,3,4,5) and (p.user_pay-p.back_money)<=3')->where($where3)->count();
            // 系统利润
            $xtlr = (float)Db::name('play_order')
                ->alias('po')
                ->join('chbc_play p','po.play_no=p.play_no')
                ->join('chbc_shop s','p.shop_no=s.shop_no')
                ->where(['po.order_status'=>['in','3,-7,-8,-9']])->where($where4)->value('sum(p.service_amt)');
            // 经纪人收益
            $orders = Db::name('play_order')
                ->alias('po')
                ->join('chbc_play p','po.play_no=p.play_no')
                ->join('chbc_shop s','po.shop_no=s.shop_no')
                ->where(['po.order_status'=>['in','3,-7,-8,-9']])->where('s.middleman_id>0')->where($where4)->field('p.service_amt,s.middleman_id')->select();
            $jjrsy = 0;
            if ($orders) {
                foreach ($orders as $order) {
                    if (isset($rebate_amt[$order['middleman_id']])) {
                        $jjrsy+=$rebate_amt[$order['middleman_id']];
                    }
                }
            }
            $jjrsy = round($jjrsy,2);
            // 实际收益
            $sjsy = $xtlr-$jjrsy;
            // 坏账金额
            $hzje = (float)Db::name('play_order')
                ->alias('po')
                ->join('chbc_shop s','po.shop_no=s.shop_no')
                ->where(['po.order_status'=>['in','3,-7,-8,-9'],'is_pay'=>0])->where('s.salesman_admin_id='.$value['id'].' and po.create_dt>="'.$start_date.'" and po.create_dt<"'.$end_date.'"')->value('sum(po.rebate_amt+po.actual_rebate_amt)');
            // 超出3%金额
            $cc3p = 0;
            if ($hzje>$sjsy*0.03) {
                $cc3p = round($hzje-$sjsy*0.03,2);
            }
            // BD坏账承担金额
            $bdcd = 0;
            if ($cc3p>0) {
                $bdcd = round($cc3p*0.2,2);
            }
            // BDM坏账承担金额
            $bdmcd = 0;
            if ($cc3p>0) {
                $bdmcd = round($cc3p-$bdcd,2);
            }
            $data = [
                'date' => date('Ymd'),
                'employee_name' => $value['nickname'],
                'employee_id' => $value['id'],
                'xzsj' => $xzsj,
                'zxyzdp' => $zxyzdp,
                'sjsy' => $sjsy,
                'xtlr' => $xtlr,
                'jjrsy' => $jjrsy,
                'hzje' => $hzje,
                'cc3p' => $cc3p,
                'bdcd' => $bdcd,
                'bdmcd' => $bdmcd,
                'city' => Db::name('shop')->where(['shop_status'=>1])->where($where2)->value('city'),
            ];
            $list[$key] = $data;
        }
        Db::name('employee_performance')->insertAll($list);
    }


    /**
     * 拉取美团官方活动订单
     * @return [type] [description]
     */
    public function mtofficialOrder()
    {
        $time = time();
        $lasthour = $time-3600;
        $bwc = new \services\BwcService();
        $platform_order_no = '';
        $query_type = 2;
        $start_time = date('Y-m-d H:i:s',$lasthour);
        $end_time = date('Y-m-d H:i:s');
        $page = 1;
        $res = $bwc->orderList($platform_order_no,$query_type,$start_time,$end_time,$page);
        // var_dump($res);exit;
            \think\Log::write('美团官方活动订单列表'.$res);
        $decode = json_decode($res,1);
        if ($decode['msg']=='SUCCESS') {
            $this->handleMtofficialOrder($decode,$platform_order_no,$query_type,$start_time,$end_time,$page);
        }
    }


    public function handleMtofficialOrder($decode,$platform_order_no,$query_type,$start_time,$end_time,$page)
    {
        // 更新订单状态
        $list = $decode['data']['list'];
        if (count($list)) {
            foreach ($list as $key => $value) {
                $platform_order_no = $value['platform_order_no'];
                $mtofficial_order = \app\common\model\Mtorder::where(['play_order_no'=>$platform_order_no])->find();
                if ($mtofficial_order['order_status']==3) {
                    continue;
                }
                $mtofficial = Db::name('mtofficial')->where(['no'=>$mtofficial_order['play_no'],'lat'=>$mtofficial_order['lat'],'lon'=>$mtofficial_order['lng']])->order('id DESC')->find();
                $content = [];
                if (isset($mtofficial['content']) && $mtofficial['content']) {
                    $content = json_decode($mtofficial['content'],1);
                }
                if (isset($content['ratio']) && $mtofficial_order) {
                    $content1 = $value;
                    unset($content1['goods']);
                    $mtofficial_order->content = json_encode($content1);
                    //用户任务状态编码(0:未报名,1:已过期,2:已取消,3:已报名,4:已下单,5:已评价,6:任务失败,100:任务完成 )
                    switch ($value['code']) {
                        case 1:
                            $mtofficial_order->order_status=-2;
                            break;
                        case 2:
                            $mtofficial_order->order_status=-1;
                            break;
                        case 3:
                            $mtofficial_order->user_pay = (float)$value['paid_amount'];
                            $ratio = floor(config('ratio_rate')*$content['ratio']/100/100)*100;
                            $actual_rebate_amt = round($value['paid_amount']*$ratio/10000,2);
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$value['order_profit'];
                            $mtofficial_order->service_charge_amt = round($value['order_profit']-$actual_rebate_amt,2);
                            $mtofficial_order->order_status=1;
                            break;
                        case 4:
                            $mtofficial_order->user_pay = (float)$value['paid_amount'];
                            $ratio = floor(config('ratio_rate')*$content['ratio']/100/100)*100;
                            $actual_rebate_amt = round($value['paid_amount']*$ratio/10000,2);
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$value['order_profit'];
                            $mtofficial_order->service_charge_amt = round($value['order_profit']-$actual_rebate_amt,2);
                            $mtofficial_order->order_status=4;
                            break;
                        case 5:
                            $mtofficial_order->user_pay = (float)$value['paid_amount'];
                            $ratio = floor(config('ratio_rate')*$content['ratio']/100/100)*100;
                            $actual_rebate_amt = round($value['paid_amount']*$ratio/10000,2);
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$value['order_profit'];
                            $mtofficial_order->service_charge_amt = round($value['order_profit']-$actual_rebate_amt,2);
                            $mtofficial_order->order_status=3;
                            break;
                        case 6:
                            $mtofficial_order->order_status=-2;
                            break;
                        case 100:
                            $mtofficial_order->user_pay = (float)$value['paid_amount'];
                            $ratio = floor(config('ratio_rate')*$content['ratio']/100/100)*100;
                            $actual_rebate_amt = round($value['paid_amount']*$ratio/10000,2);
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$value['order_profit'];
                            $mtofficial_order->service_charge_amt = round($value['order_profit']-$actual_rebate_amt,2);
                            $mtofficial_order->order_status=3;
                            break;
                    }
                    Db::startTrans();
                    try {
                        $mtofficial_order->save();
                        if (in_array($value['code'], [5,100])) {
                            $User = new \app\common\model\User();
                            $user = \app\common\model\User::where('id',$mtofficial_order['user_id'])->find();
                            // 用户获得吃豆
                            $beans = $mtofficial_order['actual_rebate_amt'];
                            $user->beans($beans,$mtofficial_order['user_id'],'下单返豆',$mtofficial_order['play_order_no']);
                            \app\common\model\MtorderLog::create([
                                'play_order_id' => $mtofficial_order['id'],
                                'play_order_no' => $mtofficial_order['play_order_no'],
                                // 'create_by' => $this->auth->nickname,
                                'create_by_id' => $mtofficial_order['user_id'],
                                'is_front' => 1,
                                'info' => '订单完成',
                            ]);
                            // 发送微信消息
                            $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                            if ($qywx) {
                                $external_userid = $qywx['ExternalUserID'];
                                $sender = $qywx['UserID'];
                                $title = '您的活动订单审核成功';
                                $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                                $url = config('h5_domain').'/#/pages/index/order';
                                $lPublics = new \app\api\service\UserService();
                                $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                            }
                            // 发送app消息
                            // if (isset($user['birthday']) && $user['birthday']) {
                                $lPublics = new \app\api\service\UserService();
                                $title = '您的活动订单审核成功';
                                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                                $url = '/pages/index/order';
                                $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$mtofficial_order->play_order_no);
                                $title = '【完成一笔订单】任务达成';
                                $desc = '获得2次抽奖机会（当日有效）';
                                $url = '/index/raffle/raffle';
                                $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                            // }
                            // 分销和抽奖机会和积分
                            // if ($order->order_status==3) {
                                if ($user['pid']) {
                                    $order_num = order_count($mtofficial_order['user_id']);
                                    if ($order_num==1) {
                                        $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                        // 上级用户新增有效团员
                                        \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $mtofficial_order['play_order_no'], '新增有效团员');
                                        // 如果是第一单，则上级用户获得一个有效用户，加积分
                                        $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                                        if (!$res) {Db::rollback();$this->error('上级用户获取积分失败');}
                                        // unipush
                                        $user2 = $User->get($user['pid']);
                                        // if (isset($user2['birthday']) && $user2['birthday']) {
                                            $lPublics = new \app\api\service\UserService();
                                            $title = '【新增一位有效团员】任务达成';
                                            $desc = '获得1次抽奖机会（当日有效）';
                                            $url = '/index/raffle/raffle';
                                            $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                        // }
                                    } elseif ($order_num==2) {
                                        $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                                    } else {
                                        $rate = (int)\think\Config::get('site.third_order');
                                        $amount = round($mtofficial_order['service_charge_amt']*$rate*0.01,2);
                                        // 当前是不是会员团长
                                        $user1 = \app\common\model\User::get($user['pid']);
                                        if ($user1['hytz']==1) {
                                            // 团长的有效用户数是否大于指定的用户数
                                            $invitation_new_reward = \think\Config::get('site.yyty');
                                            $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                            if (count($user_distribution)>$invitation_new_reward) {
                                                $ratenim = (float)\think\Config::get('site.third_order_min3');
                                            } else {
                                                $ratenim = (float)\think\Config::get('site.third_order_min2');
                                            }
                                        } else {
                                            $ratenim = (float)\think\Config::get('site.third_order_min');
                                        }
                                        if ($amount<$ratenim) $amount = $ratenim;
                                    }
                                    if ($amount) {
                                        \app\common\model\UserDistribution::create([
                                            'play_order_no' => $mtofficial_order['play_order_no'],
                                            'uid' => $mtofficial_order['user_id'],
                                            'pid' => $user['pid'],
                                            'play_no' => $mtofficial_order['play_no'],
                                            'amount' => $amount,
                                            'order_times' => $order_num,
                                        ]);
                                        // 上级用户加吃豆
                                        $res = $User->beans($amount, $user['pid'], '下级返利', $mtofficial_order['play_order_no']);
                                        if (!$res) {Db::rollback();$this->error('上级返利失败');}
                                        // 发送app消息
                                        // $user = \app\common\model\User::get($user['pid']);
                                        if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                        // if (isset($user['birthday']) && $user['birthday']) {
                                            $lPublics = new \app\api\service\UserService();
                                            $title = '团长奖励获得吃豆';
                                            $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                            $url = '/pages/user/user-data';
                                            $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                        // }
                                    }
                                }
                                // 用户加积分
                                $res = $User->score(config('order_score'),$mtofficial_order['user_id'],'下单获得');
                                if (!$res) {Db::rollback();$this->error('增加积分失败');}
                                // 完成订单
                                \app\common\model\UserLuckdrawLog::addLog($mtofficial_order['user_id'], 1, $mtofficial_order['play_order_no'], '完成订单', 2);
                            // }
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                    }
                }
            }
        }
        if ($decode['data']['page']*$decode['data']['pageSize']<$decode['data']['total']) {
            $page += 1;
            $res = $bwc->orderList($platform_order_no,$query_type,$start_time,$end_time,$page);
            \think\Log::write('美团官方活动订单列表'.$res);
            $decode = json_decode($res,1);
            if ($decode['msg']=='SUCCESS') {
                $this->handleMtofficialOrder($decode,$platform_order_no,$query_type,$start_time,$end_time,$page);
            }
        }
    }


    /**
     * 下单超时
     * @return [type] [description]
     */
    public function mtofficialOrderTimeout()
    {
        $time = time();
        Db::startTrans();
        try {
            // 下单超时
            $where = [
                'order_status'=>1,
                'expire_time'=>['<=',$time]
            ];
            $order = \app\common\model\Mtorder::where($where)->select();
            if ($order) {
                // 更新订单状态
                \app\common\model\Mtorder::where($where)->update(['order_status'=>-2,'update_by'=>'crontab1','update_dt'=>date('Y-m-d H:i:s',$time)]);
                $all = [];
                $bwc = new \services\BwcService();
                $MeituanService = new \services\MeituanService('','');
                foreach ($order as $key => $value) {
                    if ($value['is_yunzhan']==4) {
                        $res = $MeituanService->cancelevent($value['proposal'],$value['wm_order_sn']);
                    } elseif ($value['is_yunzhan']==5) {
                        $ElemService = new \services\ElemService('');
                        $res = $ElemService->stockrelease($value['wm_order_sn']);
                    } elseif ($value['is_yunzhan']==1) {
                        $res = $bwc->cancelevent($value['wm_order_sn']);
                    }
                    $all[$key]['play_order_id'] = $value['id'];
                    $all[$key]['play_order_no'] = $value['play_order_no'];
                    $all[$key]['info'] = '自动取消';
                    $all[$key]['create_by'] = 'crontab1';
                }
                // 日志
                Db::name('mtofficial_order_log')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
    }


    /**
     * 评价超时
     * @return [type] [description]
     */
    public function mtofficialOrderTimeout2()
    {
        $time = time();
        Db::startTrans();
        try {
            // 下单超时
            $where = [
                'order_status'=>4,
                'expire_time'=>['<=',$time]
            ];
            $order = \app\common\model\Mtorder::where($where)->select();
            if ($order) {
                // 更新订单状态
                \app\common\model\Mtorder::where($where)->update(['order_status'=>-2,'update_by'=>'crontab2','update_dt'=>date('Y-m-d H:i:s',$time)]);
                $all = [];
                foreach ($order as $key => $value) {
                    $all[$key]['play_order_id'] = $value['id'];
                    $all[$key]['play_order_no'] = $value['play_order_no'];
                    $all[$key]['info'] = '自动取消';
                    $all[$key]['create_by'] = 'crontab2';
                }
                // 日志
                Db::name('mtofficial_order_log')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
    }

    /**
     * 中间人佣金，发送短信和app通知
     * @return [type] [description]
     */
    public function finishOrder()
    {
        Db::startTrans();
        try {
            $order = Db::name('play_order_log')->alias('pol')->join('play_order po','po.play_order_no=pol.play_order_no')->field('po.*,pol.id as log_id,pol.is_finish')->where(['pol.info'=>'商家支付h5账单','is_finish'=>['in',[0,2]]])->select();
            // 每个店铺的支付总金额
            $sum = [];
            $order_nos = [];
            $play_nos = [];
            $User = new \app\common\model\User();
            if ($order) {
                foreach ($order as $key => $value) {
                    if (!in_array($value['play_no'], $play_nos)) {
                        $play_nos[] = $value['play_no'];
                    }
                    // 中间人佣金
                    $shop = Db::name('shop')->where(['shop_no'=>$value['shop_no']])->field('middleman_id,shop_no')->find();
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                    // 支付过佣金了就不要再支付了
                    if (Db::name('user_money_log')->where(['user_id'=>$middleman['user_id'],'tran_no'=>$value['play_order_no']])->find()) {
                        continue;
                    }
                    // 如果是大额返利，此时执行完成订单
                    $play = PlayModel::where('play_no', $value['play_no'])->find();
                    // 商家复审后返豆，发送短信，加积分，上级返利
                    if ($value['is_finish']==2) {
                        // 用户吃豆增加
                        $beans = $value['actual_rebate_amt'];
                        $User->beans($beans,$value['user_id'],'下单返豆',$value['play_order_no']);
                        // 消息处理
                        $user = $User->get($value['user_id']);
                        // 发送app消息
                        if (isset($user['birthday']) && $user['birthday']) {
                            $lPublics = new \app\api\service\UserService();
                            $title = '您的活动订单审核成功';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = '/pages/index/order';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$value['play_order_no']);
                            $title = '【完成一笔订单】任务达成';
                            $desc = '获得2次抽奖机会（当日有效）';
                            $url = '/index/raffle/raffle';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                        }
                        // 发送短信
                        // if (isset($user['mobile']) && $user['mobile']) {
                        //     $Alisms = new \addons\alisms\Alisms();
                        //     $params = [
                        //         'mobile' => $user['mobile'],
                        //         'event' => 'order_complete',
                        //         'msg' => '您好，您在吃喝不愁平台参加的外卖活动订单已通过，请知晓。',
                        //     ];
                        //     $res = $Alisms->smsNotice($params);
                        // }
                        // 订阅消息
                        // $openid = Db::name('third')->where(['user_id'=>$user['id'],'platform'=>'miniprogram'])->value('openid');
                        // if ($openid) {
                        //     $UserService = new \app\api\service\UserService();
                        //     $template_id = config('template_id.ddwctz');
                        //     $page = '/pages/index/order';
                        //     $data = [
                        //         'thing1' => ['value'=>$value['shop_name']],
                        //         'time3' => ['value'=>date('Y-m-d H:i:s')],
                        //         'character_string5' => ['value'=>$value['play_order_no']],
                        //         'phrase10' => ['value'=>'已完成'],
                        //     ];
                        //     $res = $UserService->xcxNotice($openid,$template_id,$page,$data);
                        // }
                        // 分销和抽奖机会和积分
                        // OrderLog::create([
                        //     'play_order_id' => $value['id'],
                        //     'play_order_no' => $value['play_order_no'],
                        //     'info' => '订单完成',
                        //     'create_by' => $user['nickname'],
                        //     'create_by_id' => $user['id'],
                        //     'is_front' => 1,
                        // ]);
                        // OrderModel::where(['id'=>$value['id']])->update(['order_status'=>3,'is_pay'=>1,'pay_time'=>time()]);
                        if ($user['pid']) {
                            $order_num = order_count($value['user_id']);
                            if ($order_num==1) {
                                $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                // 上级用户新增有效团员
                                \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $value['play_order_no'], '新增有效团员');
                                // 如果是第一单，则上级用户获得一个有效用户，加积分
                                $res = (new User())->score(config('invite_score'),$user['pid'],'邀请获得');
                                if (!$res) {Db::rollback();return false;}
                                // unipush
                                $user2 = $User->get($user['pid']);
                                if (isset($user2['birthday']) && $user2['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '【新增一位有效团员】任务达成';
                                    $desc = '获得1次抽奖机会（当日有效）';
                                    $url = '/index/raffle/raffle';
                                    $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                }
                            } elseif ($order_num==2) {
                                $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                            } else {
                                $rate = (int)\think\Config::get('site.third_order');
                                $amount = round($value['service_charge_amt']*$rate*0.01,2);
                                // 当前是不是会员团长
                                $user1 = \app\common\model\User::get($user['pid']);
                                if ($user1['hytz']==1) {
                                    // 团长的有效用户数是否大于指定的用户数
                                    $invitation_new_reward = \think\Config::get('site.yyty');
                                    $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                    if (count($user_distribution)>$invitation_new_reward) {
                                        $ratenim = (float)\think\Config::get('site.third_order_min3');
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min2');
                                    }
                                } else {
                                    $ratenim = (float)\think\Config::get('site.third_order_min');
                                }
                                if ($amount<$ratenim) $amount = $ratenim;
                            }
                            if ($amount) {
                                \app\common\model\UserDistribution::create([
                                    'play_order_no' => $value['play_order_no'],
                                    'uid' => $value['user_id'],
                                    'pid' => $user['pid'],
                                    'play_no' => $value['play_no'],
                                    'amount' => $amount,
                                    'order_times' => $order_num,
                                ]);
                                // 上级用户加吃豆
                                $res = (new User())->beans($amount, $user['pid'], '下级返利', $value['play_order_no']);
                                if (!$res) {Db::rollback();return false;}
                                // 发送app消息
                                if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                // if (isset($user['birthday']) && $user['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '团长奖励获得吃豆';
                                    $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                    $url = '/pages/user/user-data';
                                    $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                // }
                            }
                            // 用户加积分
                            $res = (new User())->score(config('order_score'),$value['user_id'],'下单获得');
                            if (!$res) {Db::rollback();$this->error('增加积分失败');}
                            // 完成订单
                            \app\common\model\UserLuckdrawLog::addLog($value['user_id'], 1, $value['play_order_no'], '完成订单', 2);
                        }
                    }
                    if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                        $User->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $value['play_order_no']);
                    }
                    Db::name('play_order_log')->where(['id'=>$value['log_id']])->update(['is_finish'=>1,'update_dt'=>date('Y-m-d H:i:s')]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }



    // public function superPlayEnd()
    // {
    //     $date = date('Y-m-d');// 今天0点
    //     $time = strtotime($date);
    //     $last3time = $time-259200;
    //     $last3date = date('Y-m-d H:i:s',$last3time);
    //     // $shops = Db::name('play')->field('shop_no')->where('create_dt>"'.$last3date.'" and create_dt<="'.date('Y-m-d H:i:s').'"')->group('shop_no')->select();
    //     // 已经结束的循环活动
    //     $play = Db::name('play')->where(['super_play_no'=>['>',0],'play_status'=>['in',[4,5]],'pay_status'=>3])->field('id,parent_play_no,play_no,user_id')->select();
    //     Db::startTrans();
    //     try {
    //         foreach ($play as $key => $value) {
    //             // 下级活动是否都结束,最后一个创建的下级活动距今超过三天
    //             $playing = Db::name('play')->where(['parent_play_no'=>$value['parent_play_no'],'play_status'=>2])->order('create_dt DESC')->field('id,create_dt')->find();
    //             if (isset($playing['create_dt']) && strtotime($playing)<$last3time) {
    //                 // 已结束的活动，按照没有消耗名额退还冻结金额
    //                 $sonplay = Db::name('play')->where(['parent_play_no'=>$value['parent_play_no'],'play_status'=>['in',[4,5]]])->field('id,play_no')->select();
    //                 $pay = 0;
    //                 foreach ($sonplay as $k => $v) {
    //                     $order = Db::name('play_order')->where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9,-6]]])->field('sum(actual_rebate_amt) as sum_actual_rebate_amt,sum(service_charge_amt) as sum_service_charge_amt')->find();
    //                     $pay += $order['sum_actual_rebate_amt']+$order['sum_service_charge_amt'];
    //                 }
    //                 // 返还冻结金额
    //                 $User = new \app\common\model\User();
    //                 $users = $User->field('money,freeze_money')->where(['id'=>$value['user_id']])->find();
    //                 if ($pay<=$users['freeze_money']) {
    //                     $money = -1*$pay;
    //                     $User->money($money, $value['user_id'], '冻结返还', $value['play_no'], 1);
    //                     Db::name('play')->where(['id'=>$value['id']])->update(['pay_status'=>2,'update_by'=>'crontab9']);
    //                 }
    //             }
    //         }
    //         Db::commit();
    //     } catch (\Exception $e) {
    //         Db::rollback();
    //     }
    // }
    

    // 活动没有产生订单而结束后，商家冻结金额返还余额
    public function moneyBack()
    {
        $time = time();
        $today_start = strtotime(date('Ymd',$time));
        $today_end = strtotime(date('Ymd',$time))+86399;
        Db::startTrans();
        try {
            $play = Db::name('play')->field('*')->where('play_status=4 and is_pay=1 and pay_status=3 and id>364925')->select();
            $play2 = Db::name('play')->field('*')->where('play_status=4 and is_pay=1 and pay_status=2 and super_play_no>0 and id>364925')->select();
            $play = array_merge($play,$play2);
            foreach ($play as $key => $value) {
                $user_money_log10 = Db::name('user_money_log')->where(['user_id'=>$value['user_id'],'tran_no'=>$value['play_no'],'log_type'=>10])->find();
                $user_money_log2 = Db::name('user_money_log')->where(['user_id'=>$value['user_id'],'tran_no'=>$value['play_no'],'log_type'=>2])->find();
                if ($value['num']==$value['stock'] && !$user_money_log10 && $user_money_log2) {
                    $user = Db::name('user')->where('id',$value['user_id'])->field('freeze_money')->find();
                    if ($user['freeze_money']>=abs($user_money_log2['money'])) {
                        // 冻结金额减少
                        $money = -1*abs($user_money_log2['money']);
                        (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no'], 1);
                        // 商家余额增加
                        $money = -1*$money;
                        (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no']);
                    }
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }
    }

    // 删除mtofficial超过一百万外的数据
    public function deleteMtofficial()
    {
        // 表里剩余的数据条数
        $residue = 1000000;
        // 每次删除10万
        $num=100000;
        $max = Db::name('mtofficial')->order('id DESC')->value('id');
        $min = Db::name('mtofficial')->order('id ASC')->value('id');
        $mtofficial = $max-$min;
        $diff = $mtofficial-$residue;
        if ($diff>0) {
            for ($i=1; $i < 10; $i++) { 
                $top = intval($min+$num*$i);
                if ($top<$max-$residue) {
                    Db::name('mtofficial')->where('id>='.$min.' and id<'.intval($min+$num*$i))->delete();
                }
            }
        }
    }


    /**
     * 用户最近6笔订单正常完成就不再限制
     * @return [type] [description]
     */
    public function limitdUser()
    {
        $date = date('Y-m-d H:i:s');
        $users = Db::name('user')->where(['status'=>'normal','is_limited'=>1])->field('id')->select();
        if ($users) {
            Db::startTrans();
            try {
                foreach ($users as $key => $value) {
                    $sql = 'select * from (select 1 as type,id,order_status,is_pay,create_dt from chbc_play_order where order_status in (3,-6,-7,-8,-9) and user_id='.$value['id'].' union all select 2 as type,id,order_status,is_pay,create_dt from chbc_mtofficial_order where order_status=3 and user_id='.$value['id'].')a order by create_dt DESC limit 0,6';
                    $orders = Db::query($sql);
                    $i=0;
                    foreach ($orders as $k => $v) {
                        if (in_array($v['order_status'], [-4,-6,-7,-8,-9])) {
                            $i=1;
                            break;
                        }
                    }
                    if ($i==0) {
                        Db::name('user')->where('id',$value['id'])->update(['is_limited'=>0,'updatetime'=>time()]);
                        $data = [
                            'user_id' => $value['id'],
                            'type' => '解除限制',
                            'create_dt' => $date,
                            'status' => 1,
                            'reason' => '连续6单正常',
                            'mode' => 4,
                        ];
                        Db::name('blacklist_item')->insert($data);
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
            }
        }
    }


    // 今天的活跃店铺查出来进行缓存
    public function activeShop()
    {
        $date = date('Y-m-d');
        $time = strtotime($date);
        $timestap = time();
        $shops = Db::name('play')->where('create_dt>='.$date.' and play_status=2 and chbcquota>0')->field('shop_name,start_time_str,end_time_str,chbcquota,shop_no')->group('shop_no')->select();
        $cache = '';
        $shoparr = [];
        foreach ($shops as $key => $value) {
            if ($timestap<strtotime($date.' '.$value['start_time_str']) || $timestap>=strtotime($date.' '.$value['end_time_str'])) continue;
            $cache .= $value['shop_name'].',';
            $shoparr[$value['shop_no']] = $value['shop_name'];
        }
        $cache = trim($cache,',');
        \think\Cache::store('redis')->set('bdbshops',$cache,3600);
        \think\Cache::store('redis')->set('bdbshopsarr',json_encode($shoparr,JSON_UNESCAPED_UNICODE),86400);
    }


    // 获取吃喝不愁已支付的订单
    public function payOrder()
    {
        $start = time()-86400;
        $order = Db::name('play_order')->where(['is_pay'=>1,'is_yunzhan'=>0,'pay_time'=>['>',$start]])->field('play_order_no as o,pay_time as t')->select();
        \think\Cache::store('redis')->set('payorder',json_encode($order),86400);
    }

    /**
     * 导入
     */
    public function importorder()
    {
        $token = $this->request->get('token');
        if (!$token) exit;
        if (!Db::name('admin')->where('token2',$token)->find()) exit;
        $param = $this->request->get();
        if (!$param['file'] || !$param['channel']) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $file = $param['file'];
        $filePath = UPLOADS_PATH . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        ini_set("gd.jpeg_ignore_warning", 1);
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        // $reader->setReadDataOnly(true);//设置只读

        //加载文件
        $order_data = [];
        $order_proof_data = [];
        Db::startTrans();
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            // 表头
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            // 图片
            $drawings = $currentSheet->getDrawingCollection();
            if (count($drawings) && $param['channel']!=4) {
                $this->error('表格中存在图片，请检查后再导入');
            }
            $img_data=[];
            $imageFilePath = UPLOADS_PATH . 'uploads/imgs/'.date('Ymd').'/';
            if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
                mkdir($imageFilePath, 0777, true);
            }
            // 活动名额
            $play_num = [];
            // $ossService = new \services\OssService();
            if (count($drawings)) {
                foreach ($drawings as $drawing) {
                    list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                    $imageFileName = $drawing->getCoordinates() . date('YmdHis') . mt_rand(1000, 9999);
                    switch ($drawing->getExtension()) {
                        case 'jpg':
                        case 'jpeg':
                            $imageFileName .= '.jpg';
                            $source = @imagecreatefromjpeg($drawing->getPath());
                            imagejpeg($source, $imageFilePath . $imageFileName);
                            break;
                        case 'gif':
                            $imageFileName .= '.gif';
                            $source = @imagecreatefromgif($drawing->getPath());
                            imagegif($source, $imageFilePath . $imageFileName);
                            break;
                        case 'png':
                            $imageFileName .= '.png';
                            $source = @imagecreatefrompng($drawing->getPath());
                            imagepng($source, $imageFilePath . $imageFileName);
                            break;
                    }
                    $img_data[$startRow][$startColumn] = '/uploads/imgs/'.date('Ymd').'/' . $imageFileName;
                    // $file=$ossService->upload_file_content($upload_file,$img_data[$startRow-1][$startColumn]);
                    // var_dump($file);exit;
                }
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    $group_id = 0;
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        if ($currentColumn==6) {
                            // 读取日期
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                            // 7/31/2024 11:26
                        } elseif ($currentColumn==7 && isset($img_data[$currentRow]['G'])) {
                            $val = $img_data[$currentRow]['G'];
                        } elseif ($currentColumn==8 && isset($img_data[$currentRow]['H'])) {
                            $val = $img_data[$currentRow]['H'];
                        } elseif ($currentColumn==9 && isset($img_data[$currentRow]['I'])) {
                            $val = $img_data[$currentRow]['I'];
                        } else {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        }
                        $values[$currentColumn] = is_null($val) ? '' : $val;
                    }
                    // 写入订单表
                    $order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
                    $shop = Db::name('shop')->where('id',$values[1])->field('shop_no,service_amt,salesman_admin_id')->find();
                    $shop_no = $shop['shop_no'];
                    if (!$shop_no) {
                        $this->error('店铺id：'.$values[1].'不存在');
                    }
                    $one = Db::name('shop_serviceamt')->where(['shop_no'=>$shop_no,'channel_id'=>$param['channel']])->field('service_amt,channel_name')->find();
                    $service_amt = $one['service_amt'];
                    $channel_name = $one['channel_name'];
                    if (!$service_amt) $service_amt=$shop['service_amt'];
                    $service_admin_by = Db::name('admin')->where('id',$shop['salesman_admin_id'])->value('nickname');
                    if (!$service_admin_by) $service_admin_by='';
                    $createtime=strtotime($values[6]);
                    $values[4]=trim($values[4]);
                    // 订单已存在
                    // if (Db::name('play_order')->where(['is_yunzhan'=>$param['channel'],'wm_order_sn' => $values[4]])->count()) continue;
                    if ($values[3]=='饿了么') {
                        $platform_no = 2;
                    } elseif ($values[3]=='美团') {
                        $platform_no = 1;
                    } else {
                        $platform_no = 3;
                    }
                    $data = [
                        'play_order_no' => $order_no,
                        'shop_no' => $shop_no,
                        'shop_name' => $values[2],
                        'actual_rebate_amt' => floatval($values[5]),
                        'service_charge_amt' => $service_amt,
                        'place_time' => $createtime,
                        'order_status' => 3,
                        'create_by' => 'excel',
                        'create_dt' => date('Y-m-d',$createtime).' 12:00:00',
                        'wm_order_sn' => $values[4],
                        'is_yunzhan' => $param['channel'],
                        'platform_no' => $platform_no,
                        'service_admin_id' => $shop['salesman_admin_id'],
                        'service_admin_by' => $service_admin_by,
                    ];
                    $data['scheme_no'] = empty($values[9])?'无需反馈':'图文反馈';
                    $data['rebate_amt'] = $data['actual_rebate_amt']+$data['service_charge_amt'];
                    // 活动编号
                    $data['play_no'] = 0;
                    $start_date = strtotime(date('Y-m-d',$createtime));
                    $end_date = $start_date+86399;
                    $where = ['shop_no'=>$shop_no,'start_date'=>$start_date,'end_date'=>$end_date];
                    $where['scheme_no'] = empty($values[9])?3:['in',[2,1]];
                    $where['shop_settlement'] = floatval($values[5]+$service_amt);
                    $where['channel'] = ['like','%'.$channel_name.'%'];
                    $play_no = Db::name('play')->where($where)->order('id DESC')->value('play_no');
                    if ($play_no) {
                        $data['play_no'] = $play_no;
                        if (isset($play_num[$play_no])) {
                            $play_num[$play_no]+=1;
                        } else {
                            $play_num[$play_no]=1;
                        }
                    }
                    $order_data[] = $data;
                    // 凭据表
                    $data = [
                        'shop_no' => $shop_no,
                        'play_order_no' => $order_no,
                        'wm_order_sn' => $values[4],
                        'one_image' => $values[7],
                        'two_image' => $values[8],
                        'three_image' => $values[9],
                        'back_money' => floatval($values[5]),
                        'handle_status' => 1,
                    ];
                    $order_proof_data[] = $data;
                }
            } else {
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    $group_id = 0;
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        if ($currentColumn==6) {
                            // 读取日期
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                            // 7/31/2024 11:26
                        } elseif ($currentColumn==7) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            if ($val=='暂无') $val='';
                        } elseif ($currentColumn==8) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            if ($val=='暂无') $val='';
                        } elseif ($currentColumn==9) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            if ($val=='暂无') $val='';
                        } else {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        }
                        $values[$currentColumn] = is_null($val) ? '' : $val;
                    }
                    // 写入订单表
                    $order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
                    $shop = Db::name('shop')->where('id',$values[1])->field('shop_no,service_amt,salesman_admin_id,shop_name')->find();
                    $shop_no = $shop['shop_no'];
                    if (!$shop_no) {
                        $this->error('店铺id：'.$values[1].'不存在');
                    }
                    $one = Db::name('shop_serviceamt')->where(['shop_no'=>$shop_no,'channel_id'=>$param['channel']])->field('service_amt,channel_name')->find();
                    $service_amt = $one['service_amt'];
                    $channel_name = $one['channel_name'];
                    $service_admin_by = Db::name('admin')->where('id',$shop['salesman_admin_id'])->value('nickname');
                    if (!$service_amt) $service_amt=$shop['service_amt'];
                    $createtime=strtotime($values[6]);
                    $values[4]=trim($values[4]);
                    if ($values[3]=='饿了么') {
                        $platform_no = 2;
                    } elseif ($values[3]=='美团') {
                        $platform_no = 1;
                    } else {
                        $platform_no = 3;
                    }
                    $data = [
                        'play_order_no' => $order_no,
                        'shop_no' => $shop_no,
                        'shop_name' => $shop['shop_name'],
                        'actual_rebate_amt' => floatval($values[5]),
                        'service_charge_amt' => $service_amt,
                        'place_time' => $createtime,
                        'order_status' => 3,
                        'create_by' => 'excel',
                        'create_dt' => date('Y-m-d',$createtime).' 12:00:00',
                        'wm_order_sn' => $values[4],
                        'is_yunzhan' => $param['channel'],
                        'platform_no' => $platform_no,
                        'service_admin_id' => $shop['salesman_admin_id'],
                        'service_admin_by' => $service_admin_by,
                    ];
                    $data['scheme_no'] = empty($values[9])?'无需反馈':'图文反馈';
                    $data['rebate_amt'] = $data['actual_rebate_amt']+$data['service_charge_amt'];
                    // 活动编号
                    $data['play_no'] = 0;
                    $start_date = strtotime(date('Y-m-d',$createtime));
                    $end_date = $start_date+86399;
                    $where = ['shop_no'=>$shop_no,'start_date'=>$start_date,'end_date'=>$end_date];
                    $where['scheme_no'] = empty($values[9])?3:['in',[2,1]];
                    $where['shop_settlement'] = floatval($values[5]+$service_amt);
                    $where['channel'] = ['like','%'.$channel_name.'%'];
                    $play_no = Db::name('play')->where($where)->order('id DESC')->value('play_no');
                    if ($play_no) {
                        $data['play_no'] = $play_no;
                        if (isset($play_num[$play_no])) {
                            $play_num[$play_no]+=1;
                        } else {
                            $play_num[$play_no]=1;
                        }
                    }
                    $order_data[] = $data;
                    // 凭据表
                    $data = [
                        'shop_no' => $shop_no,
                        'play_order_no' => $order_no,
                        'wm_order_sn' => $values[4],
                        'one_image' => $values[7],
                        'two_image' => $values[8],
                        'three_image' => $values[9],
                        'back_money' => floatval($values[5]),
                        'handle_status' => 1,
                    ];
                    $order_proof_data[] = $data;
                }
            }
            $OrderProof = new \app\common\model\OrderProof();
            $order = new \app\common\model\Order();
            $order->insertAll($order_data);
            $OrderProof->insertAll($order_proof_data);
            // 活动使用名额
            foreach ($play_num as $p => $pn) {
                $channelconsume = Db::name('play')->where('play_no',$p)->value('channelconsume');
                $channelconsumes = json_decode($channelconsume,1);
                $channelconsumes[$param['channel']] = $pn;
                Db::name('play')->where('play_no',$p)->update(['channelconsume'=>json_encode($channelconsumes)]);
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success('导入成功');
    }

}
